<?php

class QuotationOrderHeaderController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	public function actions()
	{
		return array(
			'suggestCountry'=>array(
				'class'=>'ext.actions.XSuggestAction',
				'modelName'=>'Customer',
				'methodName'=>'suggest',
			),
		);
	}

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			//'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			/*array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array(),
				'users'=>array('*'),
			),*/
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','viewQuotationOrderHeader','index','view','revision',
								'delete','customer','viewPDF','suggestCountry','close'),
				'users'=>array('*'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	public function actionClose(){

		$id=Yii::app()->session['quo_no'];
		$model=new QuotationOrderHeader();

		if(isset($_POST['QuotationOrderHeader']))
		{
			$po_ref=$_POST['QuotationOrderHeader']['PO_ref'];
			$flag=QuotationOrderHeader::model()->updateByPk($id,array("PO_ref"=>$po_ref));
			if($flag){
                    QuotationOrderHeader::model()->updateByPk($id,array('generate'=>1));
                    echo CJSON::encode(array(
                        'status'=>'success', 
                        'div'=>"PO Reference successfully saved"
                        ));
                    exit;
			}
		}
         
        echo CJSON::encode(array(
            'status'=>'failure', 
            'div'=>$this->renderPartial('_form_po_ref', array('model'=>$model), true)));
        exit;               
	}
	
	public function actionViewPDF($id){
		$idUser=Yii::app()->session['id']?Yii::app()->session['id']:'';
		$user = User::model()->findByPk($idUser);

		# mPDF
        $mPDF1 = Yii::app()->ePdf->mpdf();
		$model1 = QuotationOrderHeader::model()->findAll('quotation_no=:quotation_no',array(':quotation_no'=>$id));
		//foreach($model1 as $mdl1){$temp= $mdl1->purchaseOrder_id;}
		$model2 = QuotationOrderDetail::model()->findAll('quotation_no=:quotation_no', array(':quotation_no'=>$id));
		
		$this->render('quotation',array('modelHeader'=>$model1,'modelDetail'=>$model2,'user'=>$user));
		//$this->render('invoice',array('modelHeader'=>$model1,'modelDetail'=>$model2,'user'=>$user));
	}
	
	public function actionViewQuotationOrderHeader($id){
		unset(Yii::app()->session['fromStep']);
		Yii::app()->session['quo_no']=$id;//sementara

		$modelHeader=QuotationOrderHeader::model()->findAll('quotation_no=:quotation_no',array('quotation_no'=>$id));
		$modelDetail=QuotationOrderDetail::model()->findAll('quotation_no=:quotation_no',array('quotation_no'=>$id));

		$tempCurr=$modelHeader[0]['currency'];
		foreach ($modelDetail as $value) {
			$value->products->unit_sell=number_format($value->products->unit_sell*FormatingNumber::currency($tempCurr),2,'.',',');
		}

		
		$this->render('viewQuotationOrderHeader',array(
			'modelHeader'=>$modelHeader,'modelDetail'=>$modelDetail,
		));
	}

	public function actionRevision($quo_no){
		QuotationOrderHeader::model()->updateByPk($quo_no,array('generate'=>1));
		$model = $this->loadModel($quo_no);
		$model->revisi+=1;
		$model->PO_ref='';
		$model->generate=0;

		if($model->revisi==1){
			$model->quotation_no.='-'.$model->revisi;
		}else if($model->revisi>1){
			list($no, $customer, $rev) = explode("-", $model->quotation_no);
			$rev=$model->revisi;
			$model->quotation_no=$no.'-'.$customer.'-'.$rev;
		}
		$model->isNewRecord=true;
		
		if($model->save()){
			$modelDetail = QuotationOrderDetail::model()->findAll('quotation_no=:quotation_no',array('quotation_no'=>$quo_no));
			foreach ($modelDetail as $key => $value) {
				$value->detail_id=null;
				$value->quotation_no=$model->quotation_no;
				$value->isNewRecord=true;
				$value->save();
			}
			$this->redirect(array('viewQuotationOrderHeader','id'=>$model->quotation_no));
		}

	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}
	
	public function actionCustomer(){
            $model=new Customer;
            if(isset($_POST['Customer']))
			{
				if($model->save()){
                    $modelPOH=new QuotationOrderHeader;
                    $customer=new Customer;
                    $custName=$model->customer;

                    $tempDate='';
                    
                    DialogBox::closeDialogBox($custName,"quotationOrderHeader/index",$this->getQuoNo($custName));
                    return;
                    /*$this->render('create',array(
                            'model'=>$modelPOH,'quo_no'=>$this->getQuoNo(),'customer'=>$customer,'custName'=>$custName,
                    ));*/
				}
			}
            
		$this->layout = "dialoglayout";
		$this->render('_customer',array(
			'model'=>new Customer,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new QuotationOrderHeader;
		$customer=new Customer;
                $custName='+1';
                $model->date=date("Y-m-d");
                
        if(isset($_POST['QuotationOrderHeader']))
		{
			$model->attributes=$_POST['QuotationOrderHeader'];
			$modelCustomer=Customer::model()->find('customer=:customer',array('customer'=>$model->customer_name));
			$model->customer=$modelCustomer->id;
			
			if($model->save()){
				//$this->redirect(array('view','id'=>$model->quotation_no));
				Yii::app()->session['fromStep']=true;
				$this->redirect(array('/QuotationOrderDetail/create','quo_no'=>$model->quotation_no));

			}
		}
		
		$this->render('create',array(
			'model'=>$model,'quo_no'=>"",'customer'=>$customer,'custName'=>$custName,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		//$model->customer_name=$model->Customer->customer;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['QuotationOrderHeader']))
		{
			$model->attributes=$_POST['QuotationOrderHeader'];
			$model->revisi+=1;

			if($model->save()){
				$this->redirect(array('viewQuotationOrderHeader','id'=>$model->quotation_no));
			}
		}
		
		$this->render('update',array(
			'model'=>$model,'quo_no'=>$id
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		//$this->loadModel($id)->delete(); //data master tidak boleh dihapus karena untuk log
		QuotationOrderHeader::model()->updateByPk($id,array('status_delete'=>'DELETED'));//delete master data bisa dilakukan oleh super admin

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		//if(!isset($_GET['ajax']))
		
			$this->redirect(array('index'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		Yii::app()->session['controller']='quotation';
		$employee_id=Yii::app()->session['id'];
		if(isset(Yii::app()->session['adminUser']))
			$model=QuotationOrderHeader::model()->findAll('status_delete=:delete',array('delete'=>'-'));
		else
			$model=QuotationOrderHeader::model()->findAll('employee_id=:employee_id and status_delete=:delete',array('employee_id'=>$employee_id, 'delete'=>'-'));
		
		 $this->render('admin',array(
			'model'=>$model,
		 )); 
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		/*$model=new QuotationOrderHeader('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['QuotationOrderHeader']))
			$model->attributes=$_GET['QuotationOrderHeader'];

		$this->render('admin',array(
			'model'=>$model,
		));*/
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return QuotationOrderHeader the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=QuotationOrderHeader::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param QuotationOrderHeader $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='quotation-order-header-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
        
        public function getQuoNo(){
            $tempCountQuotation=count(QuotationOrderHeader::model()->findAll());
		
		$iromawi = array("","I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII");
		$temp_no='';
		if(($tempCountQuotation+1)<10)
			$temp_no='000'.($tempCountQuotation+1);
		else if(($tempCountQuotation+1)<100)
			$temp_no='00'.($tempCountQuotation+1);
		else if(($tempCountQuotation+1)<1000)
			$temp_no='0'.($tempCountQuotation+1);
		else if(($tempCountQuotation+1)>=1000)
			$temp_no=($tempCountQuotation+1);
			
                //$customer=strtoupper($customer[0]);
		
		$quo_no=($temp_no).'-?/'.strtoupper(Yii::app()->session['id']).'/'.$iromawi[(date("m")*1)].'/'.date("Y");
		return $quo_no;
        }
}
